define(window.backboneCommon.getViewDefine("creative.modalEdit"), function ($,require,Collection,tpl,ViewMaterial) {
    var defaultsOptions={
        campaignId:"",
        spreadInfo:{},
        spaceId:"",
        submitCallback:null
    };
    var pagePrivate = {
        getDefaults :function () {
            return defaultsOptions
        },
        getOptions : function (options) {
            options=$.ExtCommon.isCheckEmpty(options)?{}:options;
            return $.ExtCommon.initMergeJson(this.getDefaults(),options);
        }
    };
    var backboneView= Backbone.View.extend({
        events: {
            "change #txt_apkId": "changeApkId",
            "click #submit_modal_creativeEdit": "saveSubmit"
        },
        initialize: function () {
            this.modelAttach={};
            this.modelAttach.baseData=this.model.get("modelBaseData");
            this.modelAttach.space=this.model.get("modelSpace");
            this.listenTo(this.modelAttach.baseData, "bind:ObjMatterType", this.bindObjMatterType);
            this.listenTo(this.modelAttach.baseData, "bind:ChannelPack", this.bindChannelPack);
            this.listenTo(this.modelAttach.space, "bind:MaterialInfo", this.bindMaterial);
            this.listenTo(this.model, "bind:Info", this.bindInfo);
            this.listenTo(this.model, "save:Info", this.saveInfoCallback);
            this.render();
        },
        render:function(){
            var templateHtml=_.template(tpl);
            this.$el.html(templateHtml());
            return this;
        },
        initMain:function(options){
            this.elementModel={
                form:$("#modal_form_detailCreative"),
                pChannelPack:$("#panel_channelPack"),
                material:$("#panel_material"),
                modal:$('#modal_creativeEdit')
            };
            this.extObject={};
            this.pageData={initPage:false,materialInfo:{}};
            this.pageOptions=$.ExtCommon.initMergeJson(pagePrivate.getOptions(),options);

        },
        initViewAttach:function () {
            var self=this;
            self.viewAttach={};
            self.viewAttach.material=new ViewMaterial({pElement:"#container_material",parentElementId:"#panel_material",
                campaignId:self.pageOptions.campaignId,url:self.modelAttach.baseData.get("defUploadImgUrl"),
                changeTabCallback:function () {self._computeModalTop()},
                uploadImgCallback:function (element) {
                    self.elementModel.form.ExtParsley().validate(element);
                }
            });
        },
        initPage:function (options) {
            options=$.ExtCommon.isCheckEmpty(options)?{}:options;
            this.pageOptions=$.ExtCommon.initMergeJson(this.pageOptions,options);
            if(!this.pageData.initPage){
                this.initViewAttach();
            }
            this.hideMaterial();
            this.collection.getInfo(this.pageOptions.creativeId);
        },
        bindInfo:function () {
            var self=this;
            var result=this.model.get("dataInfo");
            self.pageData.isAdd=result.isAdd;
            self.elementModel.modal.find(".modal-title").text($.ExtCommon.getStringConnect("{0}创意",self.pageData.isAdd?"新建":"编辑"));
            self.extObject.formValue=self.elementModel.form.ExtFormValue({isRunBind:false,
                initCallback:function(dataJson) {
                    self.viewAttach.material.initValue(dataJson.materialList,dataJson.materialJson);
                    if(!self.pageData.initPage){
                        self.pageData.initPage=true;
                        self._initChannelPack();
                        self.collection.initAfterModalEdit();
                    }else{
                        var matterTypeList=self.pageData.ObjMatterType.group[self.pageOptions.spreadInfo.type.toString()];
                        self.extObject.objMatterType.replaceData(matterTypeList);
                    }
                    if(dataJson.isAndroid){self._getChannelPackData({objMatterType:dataJson.objMatterType,apkId:dataJson.apkId,initValue:dataJson.channelPack})}
                    self.collection.getMaterialInfo(self.pageOptions.spaceId);
                    self.pageData.creativeInfo=dataJson;
                    self.elementModel.form.ExtParsley("reset");
                    self._showModal();
                }
            });
            self.extObject.formValue.cleanValue();
            self.extObject.formValue.bindValueData(result.res.data);
        },

        //标的物
        bindObjMatterType:function () {
            var self=this;
            var res=self.modelAttach.baseData.get("dataObjMatterType");
            this.pageData.ObjMatterType=res.data;
            var list=res.data.group[this.pageOptions.spreadInfo.type.toString()];
            $.each(list,function (i,info) {info.disabled=true;});
            this.extObject.objMatterType=$("#panel_objMatterType").ExtRadioCheckbox({type: "radio",attrName:"objMatterType",data:list,
                initCallback:function () {
                    self.extObject.objMatterType.disabledAll();
                    self.extObject.objMatterType.setValue(self.pageOptions.spreadInfo.objMatterType,false);
                    self._changeObjMatterType();
                },
                changeCallback:function () {
                    self._changeObjMatterType();
                    self._changeMaterialByObjMatter();
                }
            });
        },
        _changeObjMatterType:function () {
            var info=this.extObject.objMatterType.getValueInfo();
            var type="ordinary";
            if(info.isOrdinary){type="ordinary"}
            else if(info.isAndroid){type="android"}
            else if(info.isIos){type="ios"}
            else if(info.isWeChat){type="weChat"}
            this.elementModel.form.find(".matter-type").hide().find(":text").removeAttr("required");
            this.elementModel.form.find(".matter-type-"+type).show().find(":text").attr("required","");
            if(type==="android"){
                var apkId=$("#txt_apkId").val();
                this.elementModel.pChannelPack.find(".loader-inner").hide();
                this.elementModel.pChannelPack.toggle(!$.ExtCommon.isCheckEmpty(apkId));
            }
        },

        changeApkId:function (e) {
            var apkId= $.trim($(e.currentTarget).val());
            this._getChannelPackData({objMatterType:this.extObject.objMatterType.getValue(),apkId:apkId,initValue:-1});
            this._getChannelPackData(apkId);
        },
        _getChannelPackData:function (param) {
            if(!$.ExtCommon.isCheckEmpty(param.apkId)){
                param.campaignId=this.pageOptions.campaignId;
                this.elementModel.pChannelPack.show().find(".loader-inner").show();
                this.extObject.channelPack.replaceData([{id:"-1",text:"正在获取数据,请稍后……"}],"-1");
                this.extObject.channelPack.disabled();
                this.collection.getChannelPack(param);
            }else{
                this.elementModel.pChannelPack.hide();
                this.extObject.channelPack.replaceData([],-1);
            }
        },
        _initChannelPack:function () {
            this.extObject.channelPack= $("#ddl_channelPack").ExtSelect2({placeholder: "-请选择-",allowClear: true,minimumResultsForSearch: 1,infoExt: {data: []}});
        },
        bindChannelPack:function () {
            var result=this.modelAttach.baseData.get("dataChannelPack");
            if(result.res.success){
                var initValue=result.req.initValue;
                this.extObject.channelPack.replaceData(result.res.data, initValue);
                this.extObject.channelPack.removeDisabled();
                this.elementModel.pChannelPack.find(".loader-inner").hide();
            }else{
                $.ExtNotify.error("获取渠道包数据失败："+result.res.msg);
            }
        },

        //素材
        bindMaterial:function () {
            var self=this;
            var res=this.modelAttach.space.get("dataMaterialInfo");
            if(res.success){
                this.pageData.materialInfo=res.data;
                if(this.pageData.materialInfo.list.length>0){
                    if(this.pageData.materialInfo.isNative){
                        var objMatterIfo=this.extObject.objMatterType.getValueInfo();
                        if($.ExtCommon.isCheckEmpty(objMatterIfo)){
                            $.each(this.pageData.ObjMatterType.list,function (i,info) {
                                if(info.id.toString()===self.pageOptions.spreadInfo.objMatterType){
                                    objMatterIfo=info;
                                }
                            })
                        }
                        this.viewAttach.material.initNative({list:this.pageData.materialInfo.list,filter:objMatterIfo.matterTypeFilter});
                    }else{
                        this.viewAttach.material.initDefault(this.pageData.materialInfo.list);
                    }
                    if(this.elementModel.material.children().length>0){
                        this.elementModel.material.parents(".form-group:first").show();
                    }else{
                        this._hideMaterialTemp();
                    }
                }else{
                    $.ExtNotify.error("该广告位的暂无素材数据");
                    this._hideMaterialTemp();
                }
            }else{
                this.pageData.materialInfo={};
                $.ExtNotify.error("该广告位的素材数据获取失败：" +res.msg);
                this.hideMaterial();
            }
        },
        _hideMaterialTemp:function () {
            this.elementModel.material.parents(".form-group:first").hide();
        },
        _changeMaterialByObjMatter:function () {
            if(!$.ExtCommon.isCheckEmpty(this.pageData.materialInfo.list) && this.pageData.materialInfo.isNative){
                var info=this.extObject.objMatterType.getValueInfo();
                this.viewAttach.material.initFilter(info.matterTypeFilter);
            }
        },
        hideMaterial:function () {
            this.elementModel.material.html("").parents(".form-group:first").hide();
            this.pageData.materialInfo={};
        },

        _checkForm:function(data){
            $.ExtNotify.destroy();
            var isExtCheck=true;
            if(data.isNative){
                var checkNative=this.viewAttach.material.checkNative();
                isExtCheck=checkNative.length===0;
            }else{
                isExtCheck=this.viewAttach.material.checkDefault();
            }
            return this.elementModel.form.ExtParsley("validate") && isExtCheck;
        },
        saveSubmit:function () {
            var ajaxData = this.elementModel.form.ExtFormValue("getValues");
            ajaxData.isNative=this.pageData.materialInfo.isNative;
            if(this._checkForm(ajaxData)) {
                ajaxData.materialList=ajaxData.isNative?this.viewAttach.material.getValueNative():this.viewAttach.material.getValueDefault();
                ajaxData.spread=this.pageOptions.spreadInfo.id;
                ajaxData.space=this.pageOptions.spaceId;
                ajaxData.campaignId=parseInt(this.pageOptions.campaignId);
                ajaxData.templateId=this.pageData.materialInfo.template;
                ajaxData.adFormat=parseInt(this.pageData.materialInfo.adFormat);
                ajaxData.objMatterType=parseInt(ajaxData.objMatterType);
                ajaxData.matterTypeInfo=this.extObject.objMatterType.getValueInfo();
                var infoOriginal = this.elementModel.form.ExtFormValue("getOriginalData");
                if (infoOriginal.id) {ajaxData.id = infoOriginal.id}
                this.collection.saveInfo(ajaxData);
                this._hideModal()
            }
        },
        saveInfoCallback:function () {
            var result=this.model.get("dataSave");
            if (result.res.success) {
                $.ExtNotify.success("保存成功!");
                var info=result.isAdd?result.res.data:result.req;
                var dataSelect={id:info.id,name:info.name};
                if(this.pageOptions.submitCallback){this.pageOptions.submitCallback(dataSelect)}
            }else{
                this._showModal();
                $.ExtNotify.error(result.res.msg);
            }
        },

        _showModal:function(){
            this.elementModel.modal.modal("show");
            this._computeModalTop();
        },
        _computeModalTop:function () {
            $.ExtAssist.modal.computeTop(this.elementModel.modal);
        },
        _hideModal: function () {
            this.elementModel.modal.modal("hide");
        }
    });
    var viewModel=function(options){
        this.collection= new Collection();
        this.model=this.collection.model;
        this.view=new backboneView({el:options.pElement,collection:this.collection,model:this.model});
        this.view.initMain(options);
    };
    viewModel.prototype={
        init:function (options) {
            this.view.initPage(options);
        }
    };
    return viewModel;
});